<script setup lang="ts">
import { useCoinStore } from '@/store/coin';
import Input from '@/components/common/Input.vue';
import Button from '@/components/common/Button.vue';
import { ElStatistic } from 'element-plus';
import 'element-plus/es/components/statistic/style/css';
import { useTransition } from '@vueuse/core'
import Tabs from '@/components/common/Tabs.vue';
import { logo, getList } from '@/apis/currency';
import { CoinItem, Logo } from '@/interfaces/currency';
import { ref, onMounted, getCurrentInstance, computed, watch, onUnmounted } from 'vue'
import { formatNumberWithThousands } from '@/utils/utils';
import router from '@/router';
import { userStore } from '@/store/user';
const source = ref(0)
const outputValue = useTransition(source, {
    duration: 1500,
})
source.value = 295120321
const currencyId = ref<string>()
const coinList = ref<CoinItem[]>([])
const logoList = ref<Logo>({})
const instance = getCurrentInstance()
const obj = computed(() => {
    let info = {} as any
    useCoinStore().coinPriceList.forEach(item => {
        info[item.coinName] = item
    })
    return info
}) as any

let currencySocket: any
const connectCurrency = () => {
    if (currencyId.value) {
        currencySocket.unsubscribe(currencyId.value, '/topic/market')
    }
    currencyId.value = Date.now().toString(36) + Math.floor(Math.random() * 1000).toString(36)
    currencySocket.subscribe(currencyId.value, `/topic/market`, (data: CoinItem) => {
        let item = coinList.value?.find(item => item.currencyPair === data.currencyPair)
        if (item) {
            item.src = "https://file.uhx.io/" + logoList.value[item.currencyPair.split('-')[0]]
            item.percentText = (item.percent * 100).toFixed(2) + '%'
            Object.assign(item, data)
        }
        item = data
    })

}

const register = () => {
    router.push('/register')
}
watch(() => userStore().currencySocket, (val) => {
    if (val) {
        if (instance) {
            currencySocket = instance.appContext.config.globalProperties.$currencySocket
            if (currencySocket.connected) {
                connectCurrency()
            }
        }
    }
}, { immediate: true })
onMounted(async () => {
    const storedCoinList = window.localStorage.getItem('coinList');
    coinList.value = storedCoinList ? JSON.parse(storedCoinList) : [];
    logoList.value = await logo()
    window.localStorage.setItem('logoList', JSON.stringify(logoList))
    const res = await getList()
    coinList.value = res.slice(0, 6).map(item => {
        item.src = "https://file.uhx.io/" + logoList.value[item.currencyPair.split('-')[0]]
        item.percentText = (item.percent * 100).toFixed(2) + '%'
        return item
    })
    window.localStorage.setItem('coinList', JSON.stringify(coinList.value))
})
onUnmounted(() => {
    if (currencySocket) {
        currencySocket.unsubscribe(currencyId.value, '/topic/market')
    }
})
</script>

<template>
    <div>
        <div class="py-[16px] sm:px-[24px] px-[16px] max-w-[1248px] mx-auto">
            <div class="flex flex-col justify-between  lg:flex-row">
                <div class="flex sm:block items-center flex-col" v-if="!userStore().userInfo.token">
                    <div class="hidden sm:block text-primary-400 font-bold">
                        <ElStatistic :value="outputValue" :value-style="{fontSize: '72px', fontWeight: 'bold', color: '#38bdf8' }"></ElStatistic>
                    </div>
                    <div class="block sm:hidden text-primary-400 font-bold">
                        <ElStatistic :value="outputValue" :value-style="{fontSize: '32px', fontWeight: 'bold', color: '#38bdf8' }"></ElStatistic>
                    </div>
                    <div class="text-[32px] font-bold sm:hidden block dark:text-[#EAECEF]">用户的共同选择</div>
                    <div class="text-[72px] font-bold h-[88px] sm:block hidden dark:text-[#EAECEF]">用户的</div>
                    <div class="text-[72px] font-bold h-[88px] sm:block hidden dark:text-[#EAECEF]">共同选择</div>
                    <div class="items-center sm:mt-[30px] mt-[20px] flex">
                        <Input class="w-[328px] sm:block hidden " placeholder="邮箱/手机号" />
                        <Button class="ml-[20px] h-[46px] leading-[46px] w-[108px] rounded-[8px]"
                            @click="register">立即注册</Button>
                    </div>
                </div>
                <div class="flex sm:block items-center flex-col" v-else>
                    <div class="sm:text-[62px] text-[32px] text-primary-400 font-bold">
                        <span>完成充值</span>
                        <span class="text-black">，畅享交易</span>
                    </div>
                    <div class="text-[32px] font-bold sm:hidden block dark:text-[#EAECEF]">用户的共同选择</div>
                    <div class="text-[72px] font-bold h-[88px] sm:block hidden dark:text-[#EAECEF]">用户的</div>
                    <div class="text-[72px] font-bold h-[88px] sm:block hidden dark:text-[#EAECEF]">共同选择</div>
                    <div class="items-center sm:mt-[30px] mt-[20px] flex">
                        <Input class="w-[328px] sm:block hidden " placeholder="邮箱/手机号" />
                        <Button class="ml-[20px] h-[46px] leading-[46px] w-[108px] rounded-[8px]"
                            @click="register">立即注册</Button>
                    </div>
                </div>
                <div
                    class="sm:dark:bg-[#29313d] w-[calc(100%)] sm:w-[calc(100%-48px)] lg:w-[454px] sm:bg-[#fafafa] mt-[20px] sm:mt-[40px] lg:mt-0 bg-transparent sm:px-[24px] sm:pt-[10px] sm:pb-[20px] sm:rounded-[12px] ">
                    <div class="flex sm:justify-between items-center justify-center">
                        <Tabs />
                        <div class="sm:block hidden text-[14px] text-[#9c9c9c]">查看全部代币</div>
                    </div>
                    <div class="sm:mt-[10px] lg:mt-[20px] mt-[10px] flex flex-col justify-between h-[calc(100%-60px)]">
                        <div v-for="(item, value) in coinList" :key="value"
                            class="sm:h-[24px] h-[28px] flex items-center justify-between sm:mt-[10px] mb-[16px] lg:mt-0 lg:mb-0"
                            :class="[value === 5 ? 'mb-0' : '']">
                            <div class="w-[45%] flex items-center">
                                <img class="sm:w-[28px] w-[24px]" :src="item.src" />
                                <div class="ml-[8px] mr-[4px] text-[16px] font-[600] dark:text-[#EAECEF]">{{
                                    item.currencyPair }}</div>
                                <!-- <div class="text-[14px] text-[#828282]">Bitcoin</div> -->
                            </div>
                            <div class=" flex-1 flex justify-end text-[16px] font-[600] dark:text-[#EAECEF]">${{
                                obj[(item.currencyPair.split('-')[0])]?.unitDecimals ?
                                    formatNumberWithThousands(item.amount.toFixed(obj[(item.currencyPair.split('-')[0])].unitDecimals))
                                    : formatNumberWithThousands(item.amount)
                            }}
                            </div>
                            <div class="flex-1 flex justify-end  text-[16px] font-[600]"
                                :class="[item.percent >= 0 ? 'text-rise' : 'text-fall']">{{ item.percent >= 0 ? '+' :
                                    ''
                                }}{{ item.percentText }}</div>
                        </div>
                    </div>
                    <div
                        class="text-[14px] flex items-center justify-center text-[#9c9c9c] sm:hidden text-center mt-[8px]">
                        <div @click="router.push('/trade')">查看全部代币</div>
                        <span class="iconfont icon-jiantou text-[12px] ml-[4px]"></span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped></style>